package com.sddongyun.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;


/**
 * @author lxt
 */

public class YbServletFilter implements Filter {
    @Autowired
    JdbcTemplate jdbcTemplate;
    private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(YbServletFilter.class);
    private static final String DOWMLOAD_FILE = "/base/downloadFile";
 
    private static final String URI ="uri";
 
//    @Autowired
//    RedisService redisService;
 
    /**
     * 超时时间
     */
//    @Value("${authorization.timeout}")
    long timeout;
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       // request.setCharacterEncoding("utf-8");
        ServletRequest requestWrapper = null;
//        log.info("当前过滤器线程名称为{}",Thread.currentThread().getName());
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse)response);
        Enumeration<String> names = request.getParameterNames();
        JSONObject endJson = new JSONObject();
        endJson.put(URI,((HttpServletRequest) request).getRequestURI());
        endJson.put("method",((HttpServletRequest) request).getMethod());
        if(names.hasMoreElements()){
            endJson.put("bodyParams" , URLDecoder.decode(((HttpServletRequest) request).getQueryString(),"utf-8"));
            endJson.put("reqDate",formatDate(new Date()));

            chain.doFilter(request, responseWrapper);
        } else {
            if(request instanceof HttpServletRequest) {
                requestWrapper = new RequestWrapper((HttpServletRequest) request);
                RequestWrapper myRequestWrapper =(RequestWrapper)requestWrapper;
                String body = myRequestWrapper.getBodyString();
                logger.info("医保请求:"+body);
                endJson.put("bodyParams",body);
                endJson.put("reqDate",formatDate(new Date()));

            }
            chain.doFilter(requestWrapper, responseWrapper);
        }
        //获取返回值
        byte[] content = responseWrapper.getContent();
        //判断是否有值
        if (content.length > 0) {
            String str = new String(content, "UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
            endJson.put("resStr",str);
            endJson.put("resDate",formatDate(new Date()));

        }else{
            endJson.put("resStr",String.valueOf(((HttpServletResponse) response).getStatus()));
            endJson.put("resDate",formatDate(new Date()));

        }
        jdbcTemplate.update(
                "insert into ybserverlog(url,reqstr,reqtime,resstr,restime) VALUES (?,?,?,?,?)"
                ,endJson.get(URI).toString()
                ,endJson.get("bodyParams").toString()
                ,endJson.get("reqDate").toString()
                ,endJson.get("resStr").toString()
                ,endJson.get("resDate").toString()
        );

    }

    public String formatDate(Date date){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
    @Override
    public void destroy() {
 
    }
}